const WebSocket = require('ws');

class Test2032Format {
    constructor() {
        this.ws = null;
        this.testResults = [];
    }

    async connect() {
        return new Promise((resolve, reject) => {
            this.ws = new WebSocket('ws://localhost:3001');
            
            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接失败:', error.message);
                reject(error);
            });

            this.ws.on('message', (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 2032) {
                        this.handle2032Response(message);
                    }
                } catch (error) {
                    console.error('❌ 消息解析失败:', error.message);
                }
            });
        });
    }

    handle2032Response(message) {
        console.log('\n📨 收到2032指令响应:');
        console.log('📋 响应格式验证:');
        
        // 检查必要字段
        const hasActId = message.hasOwnProperty('act_id');
        const hasCode = message.hasOwnProperty('code');
        const hasMsg = message.hasOwnProperty('msg');
        const hasData = message.hasOwnProperty('data');
        
        console.log(`  ✅ act_id: ${hasActId ? '✓' : '✗'} (值: ${message.act_id})`);
        console.log(`  ✅ code: ${hasCode ? '✓' : '✗'} (值: ${message.code})`);
        console.log(`  ✅ msg: ${hasMsg ? '✓' : '✗'} (值: ${message.msg})`);
        console.log(`  ✅ data: ${hasData ? '✓' : '✗'} (值: ${message.data})`);
        
        // 检查是否还有旧的gems字段
        const hasOldGems = message.hasOwnProperty('gems');
        console.log(`  ❌ gems字段: ${hasOldGems ? '✗ 应该移除' : '✓ 已移除'}`);
        
        // 验证格式
        const formatValid = hasActId && hasCode && hasMsg && hasData && !hasOldGems;
        console.log(`\n🎯 格式验证结果: ${formatValid ? '✅ 通过' : '❌ 失败'}`);
        
        if (formatValid) {
            console.log(`📝 返回内容: ${message.data}`);
            this.addTestResult('2032格式验证', true, `格式正确，data内容: ${message.data}`);
        } else {
            this.addTestResult('2032格式验证', false, '格式不符合要求');
        }
    }

    async test2032Format() {
        console.log('\n🔧 测试2032指令新格式');
        
        // 测试原木宝盒
        console.log('\n1️⃣ 测试原木宝盒 (ID: 154)');
        await this.send2032Request(154);
        await this.delay(2000);
        
        // 测试精钢宝盒
        console.log('\n2️⃣ 测试精钢宝盒 (ID: 155)');
        await this.send2032Request(155);
        await this.delay(2000);
        
        // 测试珍奇宝盒
        console.log('\n3️⃣ 测试珍奇宝盒 (ID: 156)');
        await this.send2032Request(156);
        await this.delay(2000);
        
        // 测试无效ID
        console.log('\n4️⃣ 测试无效ID (ID: 999)');
        await this.send2032Request(999);
        await this.delay(2000);
    }

    async send2032Request(id) {
        return new Promise((resolve) => {
            let responseReceived = false;
            
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 2032) {
                        responseReceived = true;
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 响应解析失败:', error.message);
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            
            const request = {
                c: 2032,
                d: { id: id }
            };
            
            console.log(`📤 发送请求: ${JSON.stringify(request)}`);
            this.ws.send(JSON.stringify(request));

            // 超时处理
            setTimeout(() => {
                if (!responseReceived) {
                    console.log('⏰ 请求超时');
                    this.addTestResult(`2032测试(ID:${id})`, false, '请求超时');
                    resolve();
                }
            }, 5000);
        });
    }

    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            timestamp: new Date().toISOString()
        });
    }

    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    printSummary() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));
        
        const successCount = this.testResults.filter(r => r.success).length;
        const totalCount = this.testResults.length;
        
        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}`);
            console.log(`   ${result.message}`);
            console.log(`   时间: ${result.timestamp}`);
            console.log('');
        });
        
        console.log(`🎯 总体结果: ${successCount}/${totalCount} 通过`);
        console.log(`📈 成功率: ${((successCount / totalCount) * 100).toFixed(1)}%`);
    }

    async run() {
        try {
            console.log('🚀 开始测试2032指令新格式');
            console.log('='.repeat(50));
            
            await this.connect();
            await this.delay(1000);
            
            await this.test2032Format();
            
            this.printSummary();
            
        } catch (error) {
            console.error('❌ 测试失败:', error.message);
        } finally {
            if (this.ws) {
                this.ws.close();
                console.log('\n🔌 WebSocket连接已关闭');
            }
        }
    }
}

// 运行测试
const tester = new Test2032Format();
tester.run().catch(console.error);
